//
//  ReportViewController.swift
//  JPWords
//
//  Created by michael on 2025/7/15.
//

import UIKit

class ReportViewController: UIViewController {

    private var titleText: String
    
    private lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor(hexString: "#1C1F1E")
        label.font = .systemFont(ofSize: 17, weight: .medium)
        label.textAlignment = .center
        label.text = titleText
        return label
    }()

    private lazy var encouragementLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor(hexString: "FFFFFF")
        label.font = .systemFont(ofSize: 18, weight: .bold)
        label.textAlignment = .center
        return label
    }()

    private lazy var progressView: BaseProgressView = {
        let view = BaseProgressView()
        view.progressTintColor = UIColor(hexString: "#15CC9D")
        view.trackTintColor = UIColor(hexString: "#FFFFFF")
        view.layer.cornerRadius = 8.5
        view.progress = 0.6
        view.height = 17
        return view
    }()

    private lazy var progressLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor(hexString: "#868F99")
        label.font = .systemFont(ofSize: 11, weight: .medium)
        label.textAlignment = .center
        return label
    }()

    private lazy var weekdayView: WeekdayView = {
        let view = WeekdayView()
        return view
    }()

    private lazy var dataCardView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(hexString: "FFFFFF")
        view.layer.cornerRadius = 20
        view.layer.shadowColor = UIColor(hexString: "000000")?.cgColor
        view.layer.shadowOpacity = 0.1
        view.layer.shadowOffset = CGSize(width: 0, height: 2)
        view.layer.shadowRadius = 10
        return view
    }()

    private lazy var shareTipView: ShareTipView = {
        let view = ShareTipView()
        return view
    }()
        
    init(title: String = "数据报告") {
        self.titleText = title
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }

    func setupUI() {
        navigationController?.navigationBar.isHidden = true
        view.backgroundColor = UIColor(hexString: "#FFFFFF")
        
        let bg = UIImageView(image: UIImage(named: "word_topbg"))
        view.addSubview(bg)
        bg.snp.makeConstraints { make in
            make.top.leading.trailing.equalToSuperview()
            make.width.equalTo(bg.snp.width).multipliedBy(1)
        }
        
        let backButton = UIButton(type: .system)
        backButton.setImage(UIImage(named: "nav_back_logo")?.withRenderingMode(.alwaysOriginal), for: .normal)
        backButton.addTarget(self, action: #selector(backButtonTapped), for: .touchUpInside)
        view.addSubview(backButton)
        
        view.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(Size.statusBarHeight + 17)
            make.centerX.equalToSuperview()
        }
        backButton.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(4)
            make.width.height.equalTo(48)
            make.centerY.equalTo(titleLabel)
        }

        let islandView = UIImageView(image: UIImage(named: "icon_island"))
        view.addSubview(islandView)
        islandView.snp.makeConstraints { make in
            make.top.equalTo(titleLabel.snp.bottom).offset(82)
            make.centerX.equalToSuperview()
        }

        view.addSubview(encouragementLabel)
        encouragementLabel.snp.makeConstraints { make in
            make.top.equalTo(titleLabel.snp.bottom).offset(40)
            make.centerX.equalToSuperview()
        }

        view.addSubview(progressView)
        progressView.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(42)
            make.trailing.equalToSuperview().inset(28)
            make.centerY.equalTo(islandView.snp.bottom).offset(13.5)
        }
        progressView.updateUI(progress: 0.6)
        
        view.addSubview(progressLabel)
        progressLabel.snp.makeConstraints { make in
            make.top.equalTo(progressView.snp.bottom).offset(7)
            make.leading.equalTo(progressView)
        }
        progressLabel.text = "本课进度 42/64"

        view.addSubview(dataCardView)
        dataCardView.snp.makeConstraints { make in
            make.top.equalTo(progressLabel.snp.bottom).offset(12)
            make.leading.bottom.trailing.equalToSuperview()
        }

        let products = [
            MyDataItem(title: "本次学词", unit: "词", countColor: UIColor(hexString: "#15CC9D"), count: 25),
            MyDataItem(title: "本次时长", unit: "min", countColor: UIColor(hexString: "#868F99"), count: 20),
            MyDataItem(title: "本课进度", unit: "%", countColor: UIColor(hexString: "#FF4B4C"), count: 62),
            MyDataItem(title: "今日学词", unit: "词", countColor: UIColor(hexString: "#1DB0F6"), count: 68),
            MyDataItem(title: "今日时长", unit: "min", countColor: UIColor(hexString: "#FE9601"), count: 79),
            MyDataItem(title: "本书进度", unit: "%", countColor: UIColor(hexString: "#5E62AC"), count: 32),
        ]
        let gridView = StackGridView<MyDataItem, MyDataItemView>(items: products, numberOfColumns: 3)
        gridView.rowSpacing = 27
        gridView.columnSpacing = 12
        gridView.configureCell = { cell, product, index in
            cell.updateUI(item: product)
            cell.snp.remakeConstraints { make in
                make.height.equalTo(75)
            }
        }
        gridView.reloadData()

        dataCardView.addSubview(gridView)
        gridView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(27)
            make.horizontalEdges.equalToSuperview().inset(27)
            make.height.equalTo(178)
        }

        dataCardView.addSubview(weekdayView)
        weekdayView.snp.makeConstraints { make in
            make.top.equalTo(gridView.snp.bottom).offset(27)
            make.horizontalEdges.equalToSuperview().inset(16)
            make.height.equalTo(88)
        }

        let saveButton = UIButton(type: .system)
        saveButton.setImage(UIImage(named: "btn_download_round")?.withRenderingMode(.alwaysOriginal), for: .normal)
        saveButton.addTarget(self, action: #selector(saveButtonTapped), for: .touchUpInside)
        view.addSubview(saveButton)
        saveButton.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(22)
            make.bottom.equalToSuperview().inset(Size.bottomSafeAreaHeight + 11)
        }

        let shareButton = UIButton(type: .system)
        shareButton.setImage(UIImage(named: "btn_share_round")?.withRenderingMode(.alwaysOriginal), for: .normal)
        shareButton.addTarget(self, action: #selector(shareButtonTapped), for: .touchUpInside)
        view.addSubview(shareButton)
        shareButton.addTarget(self, action: #selector(shareButtonTapped), for: .touchUpInside)
        view.addSubview(shareButton)
        shareButton.snp.makeConstraints { make in
            make.trailing.equalToSuperview().inset(22)
            make.bottom.equalToSuperview().inset(Size.bottomSafeAreaHeight + 11)
        }

        shareTipView.updateUI(title: "+8")
        view.addSubview(shareTipView)
        shareTipView.snp.makeConstraints { make in
            make.trailing.equalToSuperview().inset(16)
            make.bottom.equalTo(shareButton.snp.top).inset(2)
        }
    }

    @objc func backButtonTapped() {
        navigationController?.popViewController(animated: true)
    }

    @objc func saveButtonTapped() {
        
    }

    @objc func shareButtonTapped() {
        
    }

}

class BaseProgressView: UIView {
    var progress: CGFloat = 0.6 {
        didSet {
            updateUI(progress: progress)
        }
    }

    var height: CGFloat = 17 {
        didSet {
            updateUI(progress: progress)
        }
    }

    var progressTintColor: UIColor? = UIColor(hexString: "#15CC9D") {
        didSet {
            updateUI(progress: progress)
        }
    }

    var trackTintColor: UIColor? = UIColor(hexString: "#FFFFFF") {
        didSet {
            updateUI(progress: progress)
        }
    }

    var cornerRadius: CGFloat = 8.5 {
        didSet {
            updateUI(progress: progress)
        }
    }

    private let bgView: UIView = {  
        let view = UIView()
        view.backgroundColor = UIColor(hexString: "FFFFFF")
        view.layer.borderColor = UIColor(hexString: "BABDCA")?.cgColor
        return view
    }()

    private let progressView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(hexString: "#15CC9D")
        return view
    }()

    private let indicatorView: UIImageView = {
        let view = UIImageView()
        view.image = UIImage(named: "icon_ indicator_dog")
        return view
    }()

    init() {
        super.init(frame: .zero)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI() {
        layer.cornerRadius = cornerRadius
        
        addSubview(bgView)
        bgView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.height.equalTo(height)
        }
        
        addSubview(progressView)
        progressView.snp.makeConstraints { make in
            make.leading.top.bottom.equalToSuperview()
            make.width.equalTo(bgView.snp.width).multipliedBy(progress)
        }
        
        addSubview(indicatorView)
        indicatorView.snp.makeConstraints { make in
            make.centerY.equalTo(progressView.snp.top)
            make.centerX.equalTo(progressView.snp.trailing)
        }
    }

    func updateUI(progress: CGFloat) {
        progressView.backgroundColor = progressTintColor
        bgView.backgroundColor = trackTintColor
        bgView.layer.cornerRadius = cornerRadius
        progressView.layer.cornerRadius = cornerRadius
        
        progressView.snp.remakeConstraints { make in
            make.leading.top.bottom.equalToSuperview()
            make.width.equalTo(bgView.snp.width).multipliedBy(progress)
        }
        indicatorView.snp.remakeConstraints { make in
            make.centerY.equalTo(progressView.snp.top)
            make.centerX.equalTo(progressView.snp.trailing)
        }
        
    }
}


class MyDataItemView: UIView {
    
    private let titleLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor(hexString: "#000000")
        label.font = UIFont.systemFont(ofSize: 14, weight: .medium)
        return label
    }()
    
    private let countLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 36, weight: .bold)
        return label
    }()
    
    private let unitLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor(hexString: "#868F99")
        label.font = UIFont.systemFont(ofSize: 12)
        return label
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI() {
        let hStack = UIStackView(arrangedSubviews: [countLabel, unitLabel])
        hStack.axis = .horizontal
        hStack.alignment = .bottom

        let vStack = UIStackView(arrangedSubviews: [titleLabel, hStack])
        vStack.axis = .vertical
        vStack.spacing = 10
        vStack.alignment = .center
        
        addSubview(vStack)
        vStack.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }

    func updateUI(item: MyDataItem) {
        titleLabel.text = item.title
        countLabel.text = String(item.count)
        unitLabel.text = item.unit
        countLabel.textColor = item.countColor
    }
}


@objcMembers
class MyDataItem: NSObject {
    let title: String
    let unit: String
    let countColor: UIColor
    var count: Int
    
    init(title: String, unit: String, countColor: UIColor?, count: Int) {
        self.title = title
        self.unit = unit
        self.countColor = countColor ?? UIColor.black
        self.count = count
    }
}

class WeekdayView: UIView {
    init() {
        super.init(frame: .zero)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI() {
        layer.cornerRadius = 10
        layer.shadowColor = UIColor(hexString: "#000000")?.withAlphaComponent(0.1).cgColor
        layer.shadowOpacity = 1
        layer.shadowOffset = CGSize(width: 0, height: 0)
        layer.shadowRadius = 4
        
        backgroundColor = UIColor(hexString: "#FFFFFF")

        let calendar = Calendar.current
        let today = Date()
        var dayItems: [DayItem] = []
        for i in 0...6 {
            let date = calendar.date(byAdding: .day, value: -i, to: today)
            let day = calendar.component(.day, from: date!)
            let weekday = calendar.component(.weekday, from: date!)
            let japaneseWeekdays = ["月","火","水","木","金","土","日"]
            let weekdaySymbol = japaneseWeekdays[weekday - 1]
            dayItems.append(DayItem(day: day, dayName: weekdaySymbol))
        }
        dayItems.reverse()
        
        let stackView = UIStackView(arrangedSubviews: dayItems.map {
            DayItemView(isToday: $0.day == calendar.component(.day, from: today), day: $0)
        })
        stackView.axis = .horizontal
        stackView.alignment = .center
        stackView.spacing = 3
        stackView.distribution = .fill
        addSubview(stackView)
        stackView.arrangedSubviews.last?.snp.makeConstraints({ make in
            make.trailing.equalToSuperview().inset(60)
        })
        stackView.snp.makeConstraints { make in
            make.verticalEdges.equalToSuperview()
            make.horizontalEdges.equalToSuperview().inset(9)
        }
        
        let divider = UIImageView(image: UIImage(named: "divider_v_dot"))
        stackView.addArrangedSubview(divider)
        divider.snp.makeConstraints { make in
            make.width.equalTo(1)
            make.centerY.equalToSuperview()
        }
        divider.setContentHuggingPriority(.required, for: .horizontal)

        let continuousIcon = UIImageView(image: UIImage(named: "icon_fire"))
        let continuousLabel = UILabel()
        continuousLabel.textColor = UIColor(hexString: "#FF781D")
        continuousLabel.font = UIFont.systemFont(ofSize: 15, weight: .bold)
        continuousLabel.text = "0"
        let continuousTitleIcon = UIImageView(image: UIImage(named: "icon_title_continuous_check"))
        let continuousStackView = UIStackView(arrangedSubviews: [continuousIcon, continuousLabel, continuousTitleIcon])
        continuousStackView.axis = .vertical
        continuousStackView.alignment = .center
        continuousStackView.spacing = 1
        stackView.addArrangedSubview(continuousStackView)
        continuousStackView.snp.makeConstraints { make in
            make.verticalEdges.equalToSuperview().inset(11)
            make.width.equalTo(41)
        }
        
        
    }
}

class DayItemView: UIView {

    private lazy var dayLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor(hexString: "#1C1F1E")
        label.font = UIFont.systemFont(ofSize: 15, weight: .semibold)
        return label
    }()

    private lazy var dayNameLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor(hexString: "#868F99")
        label.font = UIFont.systemFont(ofSize: 10)
        return label
    }()

    private let isToday: Bool
    private let day: DayItem
    
    init(isToday: Bool, day: DayItem) {
        self.isToday = isToday
        self.day = day
        super.init(frame: .zero)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI() {
        if isToday {
            let bg = UIImageView(image: UIImage(named: "word_checkin_today"))
            bg.isHidden = !isToday
            addSubview(bg)
            bg.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
            
            dayLabel.text = "今"
            dayLabel.textColor = UIColor(hexString: "#FFFFFFF")
            dayLabel.font = UIFont.systemFont(ofSize: 15, weight: .bold)
            let icon = UIImageView(image: UIImage(named: "icon_check_today_white"))
            let stackView = UIStackView(arrangedSubviews: [dayLabel, icon])
            stackView.axis = .vertical
            stackView.alignment = .center
            stackView.spacing = 2
            addSubview(stackView)
            stackView.snp.makeConstraints { make in
                make.verticalEdges.equalToSuperview().inset(23)
                make.edges.equalToSuperview()
            }
            snp.makeConstraints { make in
                make.width.equalTo(36)
            }
            
        } else {
            dayLabel.text = String(day.day)
            dayNameLabel.text = day.dayName
            let stackView = UIStackView(arrangedSubviews: [dayLabel, dayNameLabel])
            stackView.axis = .vertical
            stackView.alignment = .center
            stackView.spacing = 5
            addSubview(stackView)
            stackView.snp.makeConstraints { make in
                make.verticalEdges.equalToSuperview().inset(23)
//                make.edges.equalToSuperview()
            }
            snp.makeConstraints { make in
                make.width.equalTo(38)
            }
        }
    }
    
}   

struct DayItem {
    let day: Int
    let dayName: String
}

class ShareTipView: UIView {
    let boundsTitleLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor(hexString: "#FFFFFF")
        label.font = UIFont.systemFont(ofSize: 10)
        return label
    }()

    init() {
        super.init(frame: .zero)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI() {
        let bg = UIImageView(image: UIImage(named: "bg_bubble"))
        addSubview(bg)
        bg.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }

        let icon = UIImageView(image: UIImage(named: "mine_point_coin_logo"))
        
        let stackView = UIStackView(arrangedSubviews: [icon, boundsTitleLabel])
        stackView.axis = .horizontal
        stackView.alignment = .center
        stackView.spacing = 4
        addSubview(stackView)
        stackView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(2)
            make.horizontalEdges.equalToSuperview().inset(11)
        }
        
        icon.snp.makeConstraints { make in
            make.width.height.equalTo(17)
        }
    }

    func updateUI(title: String) {
        boundsTitleLabel.text = title
    }
    
}


class StackGridView<Item, Cell: UIView>: UIView {
    
    // MARK: - 公开属性
    
    /// 数据项数组
    var items: [Item] = [] {
        didSet {
            reloadData()
        }
    }
    
    /// 列数
    var numberOfColumns: Int = 2 {
        didSet {
            reloadData()
        }
    }
    
    /// 行间距
    var rowSpacing: CGFloat = 8 {
        didSet {
            stackView.spacing = rowSpacing
        }
    }
    
    /// 列间距
    var columnSpacing: CGFloat = 8 {
        didSet {
            rowStackViews.forEach { $0.spacing = columnSpacing }
        }
    }
    
    /// 内容边距
    var contentInsets: UIEdgeInsets = .zero {
        didSet {
            stackView.layoutMargins = contentInsets
        }
    }
    
    /// 单元格高度（固定高度或根据宽度比例计算）
    var cellHeight: CellHeight = .fixed(100) {
        didSet {
            updateCellConstraints()
        }
    }
    
    /// 选中回调
    var onItemSelected: ((Item, Int) -> Void)?
    
    /// 配置单元格闭包
    var configureCell: ((Cell, Item, Int) -> Void)?
    
    // MARK: - 私有属性
    
    private lazy var stackView: UIStackView = {
        let stack = UIStackView()
        stack.axis = .vertical
        stack.distribution = .fill
        stack.alignment = .fill
        stack.spacing = rowSpacing
        stack.layoutMargins = contentInsets
        stack.isLayoutMarginsRelativeArrangement = true
        return stack
    }()
    
    private var rowStackViews: [UIStackView] = []
    private var cells: [Cell] = []
    private var cellConstraints: [NSLayoutConstraint] = []
    
    // MARK: - 初始化
    
    init(items: [Item] = [], numberOfColumns: Int = 2) {
        self.items = items
        self.numberOfColumns = numberOfColumns
        super.init(frame: .zero)
        setupUI()
        reloadData()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupUI()
    }
    
    // MARK: - UI 设置
    
    private func setupUI() {
        backgroundColor = .clear
        addSubview(stackView)
        
        stackView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    // MARK: - 数据重载
    
    func reloadData() {
        // 清除旧视图
        stackView.arrangedSubviews.forEach { $0.removeFromSuperview() }
        rowStackViews.removeAll()
        cells.removeAll()
        
        // 如果没有数据，直接返回
        guard !items.isEmpty else { return }
        
        // 计算需要多少行
        let numberOfRows = Int(ceil(Double(items.count) / Double(numberOfColumns)))
        
        // 创建行
        for row in 0..<numberOfRows {
            let rowStackView = UIStackView()
            rowStackView.axis = .horizontal
            rowStackView.distribution = .fillEqually
            rowStackView.alignment = .fill
            rowStackView.spacing = columnSpacing
            stackView.addArrangedSubview(rowStackView)
            rowStackViews.append(rowStackView)
            
            // 计算当前行的起始和结束索引
            let startIndex = row * numberOfColumns
            let endIndex = min(startIndex + numberOfColumns, items.count)
            
            // 添加单元格
            for index in startIndex..<endIndex {
                let item = items[index]
                let cell = Cell()
                configureCell?(cell, item, index)
                cells.append(cell)
                
                // 添加点击手势
                let tapGesture = UITapGestureRecognizer(target: self, action: #selector(cellTapped(_:)))
                cell.addGestureRecognizer(tapGesture)
                cell.isUserInteractionEnabled = true
                cell.tag = index
                
                rowStackView.addArrangedSubview(cell)
            }
        }
        
        updateCellConstraints()
    }
    
    // MARK: - 单元格高度计算
    
    enum CellHeight {
        case fixed(CGFloat)
        case aspectRatio(CGFloat) // 宽高比 (width / height)
        case dynamic((CGFloat) -> CGFloat) // 根据宽度计算高度
    }
    
    private func updateCellConstraints() {
        // 移除旧约束
        NSLayoutConstraint.deactivate(cellConstraints)
        cellConstraints.removeAll()
        
        // 如果没有单元格，直接返回
        guard !cells.isEmpty else { return }
        
        // 计算单元格宽度
        let totalHorizontalSpacing = columnSpacing * CGFloat(numberOfColumns - 1)
        let totalHorizontalInset = contentInsets.left + contentInsets.right
        let availableWidth = bounds.width - totalHorizontalSpacing - totalHorizontalInset
        let cellWidth = availableWidth / CGFloat(numberOfColumns)
        
        // 为每个单元格添加高度约束
        for cell in cells {
            let height: CGFloat
            
            switch cellHeight {
            case .fixed(let fixedHeight):
                height = fixedHeight
            case .aspectRatio(let ratio):
                height = cellWidth / ratio
            case .dynamic(let heightCalculator):
                height = heightCalculator(cellWidth)
            }
            
            let heightConstraint = cell.heightAnchor.constraint(equalToConstant: height)
            cellConstraints.append(heightConstraint)
        }
        
        NSLayoutConstraint.activate(cellConstraints)
    }
    
    // MARK: - 布局更新
    
    override func layoutSubviews() {
        super.layoutSubviews()
        updateCellConstraints()
    }
    
    // MARK: - 事件处理
    
    @objc private func cellTapped(_ sender: UITapGestureRecognizer) {
        guard let cell = sender.view as? Cell else { return }
        let index = cell.tag
        guard index >= 0 && index < items.count else { return }
        
        onItemSelected?(items[index], index)
    }
    
    // MARK: - 公开方法
    
    func cellForItem(at index: Int) -> Cell? {
        guard index >= 0 && index < cells.count else { return nil }
        return cells[index]
    }
    
    func reloadItem(at index: Int) {
        guard index >= 0 && index < items.count && index < cells.count else { return }
        let item = items[index]
        let cell = cells[index]
        configureCell?(cell, item, index)
    }
}
